package com.config;

import com.utils.Commons;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

@Component
public class MyInterceptre implements HandlerInterceptor {
    @Autowired
    private Commons commons;
    private static final Set<String> exUrl = new HashSet<>();

    static {
        exUrl.add("/login");
        exUrl.add("/toLogin");
        exUrl.add("/logout");
        exUrl.add("/uploadFile");
        exUrl.add("/downloginad");
        exUrl.add("/toUpload");
        exUrl.add("/toDownload");
        exUrl.add("/get/**");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (exUrl.contains(uri)) {
            return true;
        }
        HttpSession session = request.getSession();
        if (uri.contains("/admin")) {
            Object admin = session.getAttribute("admin");
            if (admin == null) {
                response.sendRedirect("/admin/login");
                return false;
            }
            request.setAttribute("admin", admin);
        } else {
            Object user = session.getAttribute("user");
            if (user == null) {
                response.sendRedirect("/login");
                return false;
            }
            request.setAttribute("user", user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        request.setAttribute("currentYeas", Calendar.getInstance().get(Calendar.YEAR));
        request.setAttribute("commons", commons);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, @Nullable Exception ex) throws Exception {
//        request.setAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));

    }
}